package amqplog;

import com.rabbitmq.client.Channel;
import common.ContantsConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.io.IOException;

/**
 * 监听rabbitmq消息日志, 把日志输出到控制台   "amq.rabbitmq.log" 默认提供的队列不用声明
 */
public class AmqpLogConsumer {

    public static void main(String[] args) throws IOException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ContantsConfig.MQ_HOST);
        connectionFactory.setUsername(ContantsConfig.USER);
        connectionFactory.setPassword(ContantsConfig.PASSWORD);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);



        /**
         * 队列声明
         */
        channel.queueDeclare("errors-queue", true, true, false, null);
        channel.queueDeclare("warnings-queue", true, true, false, null);
        channel.queueDeclare("info-queue", true, true, false, null);


        /**
         * 将队列绑定到日志交换器 (amq.rabbitmq.log)
         */
        channel.queueBind("errors-queue", "amq.rabbitmq.log", "error");
        channel.queueBind("warnings-queue", "amq.rabbitmq.log", "warning");
        channel.queueBind("info-queue", "amq.rabbitmq.log", "info");


        /**
         * 使用监听异步接收消息
         */
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.addQueueNames("errors-queue", "warnings-queue", "info-queue");
        container.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                System.out.println(message);
            }
        });


        container.start();
    }

}
